from main import conv
import socket
import struct
import time
import json
import os
import multiprocessing
def task(video):
    os.system(f'ffplay {video}')

#帧率计算变量
totalTime = 0
avg_frame = 0


# 读取配置文件，返回配置字典对象
def readConfig():
    with open("config.json", 'r') as load_f:
        load_dict = json.load(load_f)
        return load_dict

#传入fc文件名和服务器IP
def init(ip, port):
    #发送第一帧的标志,启动电脑端视频播放
    link = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    link.connect((ip,port))
    print("连接到ESP TCP服务器成功\r\n" )
    return link

def play(fcFileName,link,video):
    flag = True
    global totalTime, avg_frame
    res = conv.flTodic(f'fcfile/{fcFileName}')  # 读取.fc文件
    fc_len = int(res['fc_len'])  # 获取总帧数
    print(f'文件长度：{fc_len}')
    for dat in range(fc_len):
        start_time = time.perf_counter()
        recv_data = link.recv(1024)
        #播放进程
        process = multiprocessing.Process(target = task,args = (video,))
        if flag == True:
            flag = False
            process.start()
        imageCode = conv.flH2xToList(res[str(dat)])
        d2ata = struct.pack("%dB" % (len(imageCode)), *imageCode)
        # 回送一部分数据给客户端
        link.send(d2ata)
        del imageCode[:]
        end_time = time.perf_counter()
        cost = end_time - start_time
        totalTime += round(cost, 4) * 1000
        avg_frame += round((1000 / (round(cost, 4) * 1000)), 4)
        print(f'传输中：当前{dat}帧/共{fc_len}帧'
              f'约等于{round((1000 / (round(cost,4) * 1000)), 4)}FPS')
    
    print(f'传输完成 共耗时{totalTime}ms|平均帧率{round((avg_frame / fc_len), 2)}FPS')


if __name__ == "__main__":
    try:
        #第一次播放的的标志
        flag = True
        while True:
            config = readConfig()
            ip = config['host']
            port = config['port']
            video = config['video']
                #调用发送主程序,开始发送fcFileName fc文件名
                #ip port 服务器端口(电脑开热点,取电脑本地连接)
                #video   电脑同步播放的视频路径
            re = input("开始播放(回车)关闭(其它)\n>>>")
            if re == '':
                print('欢迎使用ESP32 Player 播放器')
                numList = {}
                fcdata = os.listdir('fcfile')
                for num in range(len(fcdata)):
                    numList.update({str(num): fcdata[num]})
                    print(f'序号：{str(num)}>> {numList[str(num)]}')
                inp = input('请选择想要播放的文件 输入序号按回车即可>>>')
                print(f'您选择了序号为 {inp} - {numList[str(inp)]}')
                print('准备播放，读取配置...')
                fcFileName = numList[str(inp)]
                if flag == True:
                    flag = False
                    link = init(ip=ip,port=int(port))
                play(fcFileName=fcFileName,
                        link = link,
                        video = video)
            elif flag == True:
                pass
                print("起码播放一次啊,！！")
                break
            else:
                link.close()
                print('传输完成，程序3秒后退出...')
                time.sleep(3)
                break
    except Exception as ex:
        print('发生错误： ' + ex)
        print('程序3秒后退出...')
        time.sleep(3)


